package com.bmb.editor.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TestController {

    @GetMapping("/document/files/{id}")
    public Map<String, Object> files(@PathVariable("id") String id, String access_token) {
        Map<String, Object> response = new HashMap<>();
        response.put("BaseFileName", "test.docx");
        response.put("OwnerId", "2");
        response.put("UserId", "1");
        response.put("Size", "11");
        response.put("UserCanWrite", true);
        return response;
    }

    @GetMapping("/document/files/{id}/contents")
    public void contents(HttpServletRequest request, HttpServletResponse resp, @PathVariable("id") String id, String access_token) {
        Enumeration<String> xxx = request.getHeaders("access_token");
        File file = new File("E:\\test.docx");
        //获取docx文档内容
        try (InputStream in = FileUtils.openInputStream(file); OutputStream out = resp.getOutputStream()) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/document/files/{id}/contents")
    public void save(HttpServletRequest request, @PathVariable("id") String id) {
        File file = new File("E:\\test.docx");
        try (FileOutputStream out = FileUtils.openOutputStream(file); InputStream in = request.getInputStream()) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
